package com.igeek.shop.web.login;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.igeek.shop.entity.User;
import com.igeek.shop.service.LoginService;

public class LoginServlet extends HttpServlet{

	/**
	 * 
	* @ClassName: RegistServlet  
	* @Description: 用户登录
	*
	 */
	private static final long serialVersionUID = 1L;
	private LoginService login = new LoginService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		//查询数据库中是否存在该账户
		User user = login.queryuser(username,password);
		String sessioncheckcode = (String)req.getSession().getAttribute("checkcode");
		//拿到用户输入的验证码
		String checkcode = req.getParameter("checkcode");
		if(!checkcode.equalsIgnoreCase(sessioncheckcode)){
			req.setAttribute("msg", "验证码输入错误！");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			return;
		}else{
			//继续判断，此时验证码已经输入正确
			if(user==null){
				req.setAttribute("msg", "用户名或密码错误！");
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
				return;
			}else{
				//判断是否选择了自动登录
				String remember = req.getParameter("remember");
				if(remember!=null&&remember.equals("on")){
					//需要记住用户名密码。cookie..
					Cookie cookie = new Cookie("username",user.getUsername());
					cookie.setPath("/");  //设置cookie生效的路径  所有页面都可以访问到
					cookie.setMaxAge(60*60*24*7);
					resp.addCookie(cookie);
					
				}else{
					Cookie cookie = new Cookie("username","");
					cookie.setPath("/");
					cookie.setMaxAge(0);
					resp.addCookie(cookie);
				}
				req.getSession().setAttribute("user", user);
				
				resp.sendRedirect(req.getContextPath()+"/index.jsp");
			}
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}

	
}
